<?php
	//数据库
	$servername = "mysql";
	$username = "root";
	$password = "abc123456..";
	$dbname = "studentdb";

	$conn = new mysqli($servername, $username, $password, $dbname);

	if ($conn->connect_error) {
		die("连接失败: " . $conn->connect_error);
	}

	$titletext = "";
	$message = "";
	if ($_SERVER["REQUEST_METHOD"] == "POST") {
		if (isset($_POST["action"])) {
			$action = $_POST["action"];

			//添加
			if ($action == "add") {
				$xh = $_POST["学号"];
				$xm = $_POST["姓名"];
				$age = $_POST["年龄"];
				$sex = $_POST["性别"];
				$zy = $_POST["专业"];
				$sql = "insert into Students (学号, 姓名, 年龄, 性别, 专业) values ('$xh', '$xm', '$age', '$sex', '$zy')";
				if ($conn->query($sql) === TRUE) {
					$titletext = "<h2>添加学生信息</h2>";
					$message = "<table><tr><th>学号</th><th>姓名</th><th>年龄</th><th>性别</th><th>专业</th></tr><tr><td>$xh</td><td>$xm</td><td>$age</td><td>$sex</td><td>$zy</td></tr></table>";
				} else {
					$message = "<h2>添加失败</h2>"."Error: ".$conn->error;
				}
			}

			//修改
			elseif ($action == "update") {
				$xh = $_POST["学号"];
				$xm = $_POST["姓名"];
				$age = $_POST["年龄"];
				$sex = $_POST["性别"];
				$zy = $_POST["专业"];
				$sql = "update Students set 姓名='$xm', 年龄='$age', 性别='$sex', 专业='$zy' where 学号='$xh'";
				if ($conn->query($sql) === TRUE) {
					$titletext = "<h2>修改学生信息</h2>";
					$message = "<table><tr><th>学号</th><th>姓名</th><th>年龄</th><th>性别</th><th>专业</th></tr><tr><td>$xh</td><td>$xm</td><td>$age</td><td>$sex</td><td>$zy</td></tr></table>";
				} else {
					$message = "Error: ".$conn->error;
				}
			}

			//删除
			elseif ($action == "delete") {
				$xh = $_POST["学号"];
				$sql = "delete from Students where 学号='$xh'";
				if ($conn->query($sql) === TRUE) {
					$titletext = "<h2>删除学生信息</h2>";
					$message = "<table><tr><th>学号</th></tr><tr><td>$xh</td></tr></table>";
				} else {
					$message = "Error: ".$conn->error;
				}
			}

			//查找
			elseif ($action == 'search') {
				$xh = $_POST['学号'];
				$sql = "select * from Students where 学号='$xh'";
				$result = $conn->query($sql);
				if ($result->num_rows > 0) {
					$titletext = "<h2>查找学生信息</h2>";
					$message = "<table><tr><th>学号</th><th>姓名</th><th>年龄</th><th>性别</th><th>专业</th></tr>";
					while ($row = $result->fetch_assoc()) {
						$message .= "<tr><td>".$row["学号"]."</td><td>".$row["姓名"]."</td><td>".$row["年龄"]."</td><td>".$row["性别"]."</td><td>".$row["专业"]."</td></tr>";
					}
					$message .= "</table>";
				} else {
					$message = "<h2>查找失败</h2>"."表中查无此人";
				}
			}

			//转到end.php并传消息
			header("Location: end.php?titletext=".urlencode($titletext)."&message=".urlencode($message));
			exit();
		}
	}

	$conn->close();
?>
